
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
layui.use(['tableEdit',"excel","selectInput"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel,
        selectInput = layui.selectInput;

    let operationList=[];
    let salesmanList=[];
    let deptSalesmanList = [];
    let deptOperationList=[];
    //单据类型
    let statusList = [];
    //价格术语
    let priceTermsList = [];
    //业务模式
    let businessModelList = [];
    //签约公司
    let signingCompanyList = [];
    //币种
    let currencyDataList = [];
    
    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            filterable: true,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    function xmSelectData(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            toolbar:{
                show:true,
                list:['ALL', 'CLEAR']
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    //客户名称
    let ins = selectInput.render({
        elem: '#customerSelect',
        name: 'customerSelect',
        hasSelectIcon: true,
        placeholder: '请输入名称',
        data: [],
    })
    let customerInfo = [];
    //监听输入
    ins.on('itemInput(customerSelect)', function (obj) {
        let tempData = [];
        $.ajax({
            url: "basicInformation/getCustomerInfo?info=" + obj.value,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    customerInfo = res.data.customerInfo;
                    for (let i in customerInfo) {
                        customerInfo[i]["value"] = customerInfo[i].code;
                        tempData.push(customerInfo[i]);
                    }
                }
            }
        })
        ins.addSelect(tempData)
    })

    // 监听select 选择事件
    ins.on('itemSelect(customerSelect)', function (obj) {
        let code = obj.data;
        $("#customerCode").val(code);
    });

    layer.ready(function () {
        //单据类型
        let statusOptions = [
            {name: "草稿箱", value: "1"},
            {name: "待批箱", value: "2"},
            {name: "已批箱", value: "3"},
            {name: "完成箱", value: "4"},
            {name: "中止箱", value: "6"}
        ];
        statusList = xmSelectData("#status", "status", statusOptions);

        //获取价格术语信息
        $.ajax({
            url:"offer/getPriceTerms",
            success:function(data){
                if(data.status == 200){
                    let priceTermsData = [];
                    for(let i in data.data){
                        let tmp = {
                            name:data.data[i].name,
                            value:data.data[i].code
                        }
                        priceTermsData.push(tmp);
                    }
                    priceTermsList = xmSelectData("#priceTermsCode", "priceTermsCode", priceTermsData);
                    form.render('select');
                }
            }
        });

        //获取业务模式信息
        $.ajax({
            url: "offer/getBusinessModel",
            async: false,
            success: function (data) {
                if (data.status == 200) {
                    let businessModelData = [];
                    for (let i in data.data) {
                        if(data.data[i].name!="备货入库"){
                            let tmp = {
                                name: data.data[i].name,
                                value: data.data[i].code
                            }
                            businessModelData.push(tmp);
                        }
                    }
                    businessModelList = xmSelectData("#businessModelCode", "businessModelCode", businessModelData);
                    form.render('select');
                }
            }
        });

        //获取所有公司信息
        $.ajax({
            url: "receivePayment/getCompanyInfo",
            success: function (data) {
                if (data.status == 200) {
                    let signingCompanyData = [];
                    for (let i in data.data) {
                        let tmpSigning = {
                            name:data.data[i].name,
                            value:data.data[i].code
                        }
                        signingCompanyData.push(tmpSigning);
                    }
                    signingCompanyList = xmSelectData("#signingCompanyCode", "signingCompanyCode", signingCompanyData);
                    form.render('select');
                }
            }
        });

        //获取币种
        $.ajax({
            url:"receivePayment/getCurrencyInfo",
            success:function(data){
                if(data.status == 200){
                    let currencyData = [];
                    for(let i in data.data){
                        let tmpCurrencyData = {
                            name:data.data[i].name,
                            value:data.data[i].code
                        }
                        currencyData.push(tmpCurrencyData);
                    }
                    currencyDataList = xmSelectData("#currencyCode", "currencyCode", currencyData);
                    form.render('select');
                }
            }
        });

        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();

        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            operationList=getxmselect("#operationCode", "operationCode", userTree);
            salesmanList=getxmselect("#salesmanCode", "salesmanCode", userTree);
        } else {
            operationList=getxmselect("#operationCode", "operationCode", [{name: user.name, value: user.code}])
            salesmanList=getxmselect("#salesmanCode", "salesmanCode", [{name: user.name, value: user.code}]);
        }


        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        } else {
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
        }


    });
    form.render();//表单刷新

    let initData = [];
    table.render({
        elem: '#offerselect'
        , data: initData
        , toolbar: '#offertoolbar'
        , totalRow: true
        , cols: [[
            //以外销主表为主
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            , {field: 'businessModelName', title: '业务模式', sort: true, width: 120, event: "quotationno"}
            , {field: 'billNo', title: '外销合同号', sort: true, width: 220}
            , {field: 'signingDate', title: '签约日期', sort: true, width: 120}
            , {field: 'customerName', title: '客户名称', sort: true, width: 120}
            , {field: 'customerCode', title: '客户编码', sort: true, width: 120}
            , {field: 'salesmanName', title: '业务员', sort: true, width: 120}
            , {field: 'operator', title: '操作员', sort: true, width: 120}
            , {field: 'priceTermsName', title: '价格术语', sort: true, width: 120}
            , {field: 'currency', title: '外销币种', sort: true, width: 120}
            , {field: 'rmbRate', title: '人民币汇率', sort: true, width: 120}
            , {field: 'usdRate', title: '美元汇率', sort: true, width: 120}
            , {field: 'totalContractAmount', title: '外销总额', sort: true, width: 120, totalRow: true}
            , {field: 'totalContractAmountUSD', title: '外销总额(USD)', sort: true, width: 120, totalRow: true}
            , {field: 'totalContractAmountRMB', title: '外销总额(RMB)', sort: true, width: 120, totalRow: true}
            , {field: 'exportPrdtSum', title: '外销产品总额', sort: true, width: 120, totalRow: true}
            , {field: 'exportCostSum', title: '外销费用', sort: true, width: 120, totalRow: true}
            , {field: 'productNum', title: '外销数量', sort: true, width: 120, totalRow: true}
            , {field: 'receivePaymentCollectionAmountSum', title: '收款金额', sort: true, width: 120, totalRow: true}
            , {field: 'unReceivePaymentCollectionAmountSum', title: '未收款金额(外销)', sort: true, width: 120, totalRow: true}
            , {field: 'unReceivePaymentBillExchangeSum', title: '未收款金额(结汇)', sort: true, width: 120, totalRow: true}
            , {field: 'receivePaymentCollectionClaimDate', title: '最后一次水单认领日期', sort: true, width: 180}
            , {field: 'purchaseNo', title: '采购单号', sort: true, width: 220}
            , {field: 'purchaseAmountSum', title: '采购数量', sort: true, width: 120, totalRow: true}
            , {field: 'purchasePrdtAndPartsSum', title: '采购成本总额', sort: true, width: 120, totalRow: true}
            , {field: 'carryProductNum', title: '出运数量', sort: true, width: 120, totalRow: true}
            , {field: 'costSubtotal', title: '出运产品总额', sort: true, width: 120, totalRow: true}
            , {field: 'carryCostSum', title: '出运费用', width: 120, totalRow: true}
            , {field: 'billExchangeNo', title: '结汇发票号', sort: true, width: 220}
            , {field: 'moneySubtotal', title: '结汇产品总额', sort: true, width: 120, totalRow: true}
            , {field: 'costMoney', title: '结汇费用', sort: true, width: 120, totalRow: true}
            , {field: 'moneySubtotalRMB', title: '结汇总额(RMB)', sort: true, width: 120, totalRow: true}
            , {field: 'goodsNum', title: '结汇数量', sort: true, width: 120, totalRow: true}
            , {field: 'signingCompanyName', title: '签约公司', sort: true, width: 180}
            , {field: 'purchaseLastAmount', title: '采购剩余数量', sort: true, width: 120, totalRow: true}
            , {field: 'carryLastAmount', title: '出运剩余数量', sort: true, width: 120, totalRow: true}
            , {field: 'billExchangeLastAmount', title: '结汇剩余数量', sort: true, width: 120, totalRow: true}
            , {field: 'invoiceDate', title: '最后一次结汇日期', sort: true, width: 180}
            , {field: 'marginalGrossMarginContract', title: '边际毛利率%(外销)', sort: true, width: 180}
            , {field: 'marginalGrossMarginExchange', title: '边际毛利率%(结汇)', sort: true, width: 180}
        ]]
        , id: 'offertableid'
        , height: $(document).height() - $('#offerselect').offset().top - 50
        , page: true
        , limit: 300
        , limits: [300, 600, 900]
    });

    /*table.on('tool(offertable)', function(obj){
        let data = obj.data;
        let id = data.id;
        if (obj.event === "quotationno"){
            parent.intab("views/jsp/ExportBusiness/tpl/viewexport.jsp?id="+id,"外销明细")
        }
    });*/


    form.on('submit(submitform)', function (data) {
        table.reload('offertableid', {
            page: {
                limit: 300,
                curr: 1 //重新从第 1 页开始
            }
            , url: 'receivePayment/statistics/getOrderDetailByPage'
            , where: data.field
        }, 'data');
        return false;
    });

    form.on('submit(exportData)', function (queryReq) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"receivePayment/export/getContractStatisticsFQExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 120,
                        'AQ': 120
                    }, 120);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, 'FQ利润统计表.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });

    document.getElementById('clear').onclick = function(){
        operationList.setValue([ ]);
        salesmanList.setValue([ ]);
        deptSalesmanList.setValue([ ]);
        deptOperationList.setValue([ ]);
        statusList.setValue([ ]);
        priceTermsList.setValue([ ]);
        businessModelList.setValue([ ]);
        signingCompanyList.setValue([ ]);
        currencyDataList.setValue([ ]);
    };
});